package at.ac.uniklu.rallyemaster.activities;

import java.util.ArrayList;

import android.app.ListActivity;
import android.content.Intent;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import at.ac.uniklu.rallyemaster.R;
import at.ac.uniklu.rallyemaster.RallyeMaster;
import at.ac.uniklu.rallyemaster.adapters.DBTrack;
import at.ac.uniklu.rallyemaster.adapters.RallyeDBAdapter;
import at.ac.uniklu.rallyemaster.domain.Track;

public class ListTrackActivity  extends ListActivity{
	//Menu Variables
	static final private int ADD_ITEM = Menu.FIRST; 
	static final private int OPTIONS_ITEM = Menu.FIRST +1;
	
	private static final int CONTEXT_DELETE = Menu.FIRST;
	
	private RallyeDBAdapter myDBAdapter;
	private DBTrack dbTrack;
	
	private ArrayList<Track> tracks;
	private String[] listNames;
	
	private ListView listView;
	private ArrayAdapter<String> arrayAdapter;
	private int selected;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_layout);
		
		listView = (ListView) findViewById(android.R.id.list);
		registerForContextMenu(listView);
		
		// Create an array of Strings, that will be put to our ListActivity
		//RallyeMaster.logDebug("DB opening");
		myDBAdapter = new RallyeDBAdapter(this); 
		//RallyeMaster.logDebug("DB open");
		myDBAdapter.open();// move to TrackListActivity
		
		dbTrack = new DBTrack();
		
		// getting all tracks from the database
		tracks = new ArrayList<Track>();
		tracks = dbTrack.getAllTracks();
		
		// Getting track names from database tracks 
		listNames = gettingNamesforList(tracks);
			
		// Create an ArrayAdapter, that will actually make the Strings above
		// appear in the ListView
		arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listNames);
		this.setListAdapter(arrayAdapter);
				
		
		// Register an observer to handle the case where the list contents change
        getListAdapter().registerDataSetObserver(new DataSetObserver() {
            @Override
            public void onChanged() {
                // NEEDSWORK: how do we respond when the data set changes?
                configureView();
            }
        });
 
	}
	/*
	 * Fills the String Array with the track names from the database
	 */
	private String[] gettingNamesforList(ArrayList<Track> tracks){
		String[] names = new String[tracks.size()];
		for(int i = 0; i< tracks.size(); i++){
			//RallyeMaster.logDebug(tracks.get(i).getName());
			names[i]= tracks.get(i).getName();
		}
		
		return names;
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		// Get the item that was clicked
		 Track clickedTrack = tracks.get(position);
		//Toast.makeText(this, "You selected: " + keyword, Toast.LENGTH_LONG).show();
		Intent intent = new Intent(ListTrackActivity.this, ShowTrackActivity.class);
		intent.putExtra("TrackID", clickedTrack.getId());
		startActivity(intent);
		RallyeMaster.logDebug("TrackingActivity opened");
	}
	
	
	
    private void configureView() {
        View list = getListView();
        View text = findViewById(android.R.id.empty);

        if (getListAdapter().getCount() <= 0) {
            // No animals in list -- show text view
            list.setVisibility(View.GONE);
            text.setVisibility(View.VISIBLE);
        } else {
            // Animals in list -- show list view
            list.setVisibility(View.VISIBLE);
            text.setVisibility(View.GONE);
        }
    }
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		//Create and add new Items to the menu
		MenuItem loadItem = menu.add(0, ADD_ITEM, Menu.NONE,R.string.itemMenu_add);
		MenuItem optionsItem = menu.add(0, OPTIONS_ITEM, Menu.NONE,R.string.itemMenu_options);
		
		loadItem.setIcon(android.R.drawable.ic_menu_myplaces);
		optionsItem.setIcon(android.R.drawable.ic_menu_preferences);
		
		return true;
	}
	
	

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch(item.getItemId()){
			case ADD_ITEM : {
				RallyeMaster.logDebug("Load optionsmenu item clicked");
				//TODO: Open the LoadTrackActivity
				Intent intent = new Intent(ListTrackActivity.this, StoreTrackActivity.class);
				startActivity(intent);
				return true;
			}
			case OPTIONS_ITEM:{
				Intent intent = new Intent(ListTrackActivity.this, PreferencesActivity.class);
				startActivity(intent);
				return true;
			}
		}
		return false;
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		
		switch(item.getItemId()){
			case CONTEXT_DELETE:{
				dbTrack.removeTrack(tracks.get(selected).getId());
				RallyeMaster.logDebug("Selected Track: "+ tracks.get(selected).getId() + " " + tracks.get(selected).getName() );
				tracks = dbTrack.getAllTracks();
				listNames = gettingNamesforList(tracks);
				arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listNames);
				this.setListAdapter(arrayAdapter);
				arrayAdapter.notifyDataSetChanged();
				listView.invalidate();
			}
		}
		return super.onContextItemSelected(item);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
		menu.setHeaderTitle(tracks.get(info.position).getName());
		menu.add(0, CONTEXT_DELETE,0, R.string.context_menu_delete);
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	
	

}
